package com.onlinelearn.chatservice.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeacherChatService {
    @Autowired
    private ChatRepository chatRepository;

    @Autowired
    private FAQRepository faqRepository;

    public ChatMessage replyToStudent(Long teacherId, Long courseId, Long studentId, String content) {
        ChatMessage replyMessage = new ChatMessage();
        replyMessage.setSenderId(teacherId);
        replyMessage.setCourseId(courseId);
        replyMessage.setRecipientId(studentId);
        replyMessage.setContent(content);
        replyMessage.setType(MessageType.TEXT);
        replyMessage.setTimestamp(LocalDateTime.now());

        chatRepository.save(replyMessage);

        return replyMessage;
    }

    public FAQ createFAQFromChat(Long teacherId, ChatMessage originalMessage) {
        FAQ faq = new FAQ();
        faq.setCourseId(originalMessage.getCourseId());
        faq.setQuestion(originalMessage.getContent());
        faq.setAnswer(originalMessage.getReplyContent());
        faq.setTeacherId(teacherId);
        faq.setCreatedAt(LocalDateTime.now());

        return faqRepository.save(faq);
    }

    public void markQuestionResolved(Long messageId) {
        ChatMessage message = chatRepository.findById(messageId)
            .orElseThrow(() -> new ChatMessageNotFoundException(messageId));
        
        message.setStatus(ChatMessageStatus.RESOLVED);
        chatRepository.save(message);
    }

    public List<FAQ> getCourseFAQs(Long courseId) {
        return faqRepository.findByCourseId(courseId);
    }
}

enum ChatMessageStatus {
    OPEN,
    REPLIED,
    RESOLVED
} 